from werkzeug.exceptions import NotFound as HtmlNotFound

from cc_flask.request_handle import ResponseBase
from cc_flask.exception import RequiredParametersError, ErrCode, NotFound
from flask import current_app


def error_handler(error):
    """ 全局异常处理方法 """

    if isinstance(error, HtmlNotFound):
        return error

    if current_app.config.get("DEBUG"):
        import traceback
        traceback.print_exc()

    if isinstance(error, RequiredParametersError):
        return ResponseBase.error(
            ErrCode.PARAMETER_ERROR,
            err_msg='、'.join(error.args),
            data=error.data,
            err_cmsg="必填参数：%s" % '、'.join([i["describe"] for i in error.data])
        )
    if isinstance(error, NotFound):
        return ResponseBase.error(
            ErrCode.NOT_FOUND, '、'.join(error.args), data=error.data,
            err_cmsg="对象不存在或已被删除！"
        )

    return ResponseBase.error(-1, "接口出错：%s" % '、'.join(error.args), err_cmsg='出错啦！请稍后重试')
